package org.beangle.notification.service

import org.beangle.notification.Message
import org.beangle.notification.MessageQueue
import org.beangle.notification.NotificationException
import org.beangle.notification.NotificationTask
import org.beangle.notification.Notifier
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.beangle.commons.logging.Logging

class DefaultNotificationTask[T <: Message] extends NotificationTask[T] with Logging {

  private var queue: MessageQueue[T] = new DefaultMessageQueue[T]()

  var notifier: Notifier[T] = _

  private var observer: SendingObserver = _

  private var taskInterval: Long = 0

  def messageQueue(): MessageQueue[T] = queue

  def messageQueue_=(messageQueue: MessageQueue[T]) {
    this.queue = messageQueue
  }

  def send() {
    var msg = queue.poll()
    while (null != msg) {
      try {
        if (null != observer) observer.onStart(msg)
        notifier.deliver(msg)
        if (taskInterval > 0) {
          Thread.sleep(taskInterval)
        }
      } catch {
        case e: NotificationException => //logger.error("send error", e)
        case e: InterruptedException => //logger.error("send error", e)
      }
      if (null != observer) observer.onFinish(msg)
      msg = queue.poll()
    }
  }
}
